package com.google.code.stalkernet.example.ui.util;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SocketAddressUtils
{
    private final static Pattern SOCKET_ADDRESS_PATTERN =
        Pattern.compile ("(?:([^:]+|\\[[^\\[\\]]+\\]):)?([0-9]+)");

    private SocketAddressUtils ()
    {
        throw new Error ("Do not instantiate me");
    }

    public static SocketAddress parseSocketAddress (String socketAddressString)
        throws UnknownHostException
    {
        if (socketAddressString == null)
            throw new IllegalArgumentException (
               "Socket address string is null");

        Matcher matcher = SOCKET_ADDRESS_PATTERN.matcher (socketAddressString);

        if (matcher.matches ())
        {
            String host = matcher.group (1);
            int port = Integer.parseInt (matcher.group (2));

            if (host != null) return new InetSocketAddress (
                InetAddress.getByName (host), port);
            else return new InetSocketAddress (port);
        }
        else throw new IllegalArgumentException (
            "Invalid socket address string");
    }
}
